import fs = require('fs');
import md5 = require('md5');

export default class WebCommon {
    
    public static checkTempFile(filepath:string, callback:((ret:boolean)=>void)):void{
        fs.exists('views/'+filepath+'.ejs', (result) => { 
            if(callback){
                callback(result);
            }
        });
    }

    public static isEmpty(obj:{[key:string]:any}) {
        for(let item in obj) {
            return false;
        }
        return true;
    }

    public static arrayContains(arrayObj:any[], obj:any){
        for(let i = 0; i < arrayObj.length; i++){
            if(obj == arrayObj[i]){
                return true;
            }
        }
        return false;
    }

    public static getAppKey(appid:string):string{
        var salt = "Y4QTEwRkUxQzNDNe";
        var origin = appid+salt+appid;
        return md5(origin);
    }
    
    public static checkParam(paramObj:{[key:string]:any}):{[key:string]:any}{
        var appid = paramObj['appid'];
        var param = paramObj['param'];
        var token = paramObj['token'];

        if(!appid  || !param || !token){
            return { "result": false, "msg": "必须的参数有缺失"};
        }
        var appkey = this.getAppKey(appid);
        if(token != md5(appid + appkey + param + appkey)) {
            return { "result": false , "msg": "token错误"};
        }
        try{
            param = JSON.parse(param);
            param["appid"] = appid;
        }
        catch(e){
            return { "result": false , "msg": "Error:"+e.message};
        }

        return param;
    }
    public static GenerateRandomCode(len:number):string{
        var baseCode = "23456789ABCDEFGHJKLMNPQRTSUVWXYZ";
        var retStr = "";
        for(var i = 0; i < len; i++){
            var rnd = Math.floor(Math.random() * 100000) % baseCode.length;
            retStr += baseCode[rnd];
        }
        return retStr;
    }
}